﻿using System;
using System.Data;
using System.Data.Common;
using System.Configuration;
using yq.IBase.DBHelper.Paging;
using yq.CacheHelp;
using System.Reflection;
using yq.IBase.DBHelper;
using System.Collections.Generic;

namespace yq.IBase
{
    /// <summary>
    /// 数据库链接对象
    /// </summary>
    public class DbHelper : IDisposable
    {
        /// <summary>
        /// 数据库链接模式
        /// </summary>
        internal static string dbProviderName { get; private set; }


        /// <summary>
        /// 只读库地址列表
        /// </summary>
        internal static List<string> DbHelperConnectionReadList { get; private set; }

        /// <summary>
        /// 随机获取一个只读库地址
        /// </summary>
        internal static string DbHelperConnectionRead
        {
            get
            {
               return  DbHelperConnectionReadList.ToRandom();
            }
        }

        /// <summary>
        /// 写库地址
        /// </summary>
        internal static string DbHelperConnectionWrite { get; private set; }

        /// <summary>
        /// 链接对象
        /// </summary>
        public DbConnection Connection;

        TransType _TransType = TransType.Close;

        /// <summary>
        /// 当前事务状态
        /// </summary>
        internal TransType TransType
        {
            get { return _TransType; }
            set { _TransType = value; }
        }

        /// <summary>
        /// 事务
        /// </summary>
        protected DbTransaction dbTrans = null;

        /// <summary>
        /// 缓存类 可以通过这个直接操作缓存
        /// 用于数据库内容和缓存的同步
        /// </summary>
        private CaCheRefresh _CaCheRefresh = new CaCheRefresh();

        /// <summary>
        /// 缓存操作日志
        /// </summary>
        public CaCheRefresh CaCheRefresh
        {
            get { return _CaCheRefresh; }
            set { _CaCheRefresh = value; }
        }


        private IList<string> _SqlLog = new List<string>();

        /// <summary>
        /// 执行sql的记录
        /// </summary>
        public IList<string> SqlLog
        {
            get { return _SqlLog; }
            set { _SqlLog = value; }
        }


        #region 初始化

        static DbHelper()
        {
            dbProviderName = ConfigurationManager.AppSettings["DbHelperProvider"];

            string connectionRead = ConfigurationManager.AppSettings["DbHelperConnectionRead"];

            if (string.IsNullOrEmpty(connectionRead)==false)
            {
                List<string> readList = new List<string>();
                foreach (var connection in connectionRead.Split(char.Parse(",")))
                {
                    if (string.IsNullOrEmpty(connection) == false)
                    {
                        readList.Add(connection);
                    }
                }
                DbHelperConnectionReadList = readList;
            }

            DbHelperConnectionWrite = ConfigurationManager.AppSettings["DbHelperConnectionWrite"];
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public DbHelper()
        {
            this.Connection = CreateConnection(DbHelper.DbHelperConnectionRead);
        }

        /// <summary>
        /// 构造数据库链接对象
        /// </summary>
        /// <param name="connectionString">链接字符串</param>
        public DbHelper(string connectionString)
        {
            this.Connection = CreateConnection(connectionString);
        }

        /// <summary>
        /// 构造数据库链接对象
        /// </summary>
        /// <param name="connectionString">链接字符串</param>
        /// <param name="dbProviderName">链接方式</param>
        public DbHelper(string connectionString, string dbProviderName)
        {
            DbHelper.dbProviderName = dbProviderName;
            this.Connection = CreateConnection(connectionString, dbProviderName);
        }

        /// <summary>
        /// 事物初始化支持
        /// </summary>
        /// <param name="_t"></param>
        public DbHelper(DBTrans _t)
        {
            TransType = TransType.Open;
            this.Connection = _t.DbConnection;
            this.dbTrans = _t.DbTrans;
        }

        public static DbConnection CreateConnection()
        {
            //默认打开读库
            return CreateConnection(DbHelper.DbHelperConnectionRead, DbHelper.dbProviderName);
        }

        public static DbConnection CreateConnection(string connectionString)
        {
            return CreateConnection(connectionString, DbHelper.dbProviderName);
        }

        public static DbConnection CreateConnection(string connectionString, string dbProviderName)
        {

            //创建工厂
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(dbProviderName);
            DbConnection dbconn = dbfactory.CreateConnection();
            dbconn.ConnectionString = connectionString;
            return dbconn;
        }

        #endregion

        #region 获取执行对象

        /// <summary>
        /// 储存过程
        /// </summary>
        /// <param name="storedProcedure"></param>
        /// <returns></returns>
        internal DbCommand GetStoredProcCommond(string storedProcedure)
        {
            DbCommand dbCommand = Connection.CreateCommand();
            dbCommand.CommandText = storedProcedure;
            dbCommand.CommandType = CommandType.StoredProcedure;
            return dbCommand;
        }

        /// <summary>
        /// 语句
        /// </summary>
        /// <param name="sqlQuery"></param>
        /// <returns></returns>
        internal DbCommand GetSqlStringCommond(string sqlQuery)
        {
            DbCommand dbCommand = Connection.CreateCommand();
            dbCommand.CommandText = sqlQuery;
            dbCommand.CommandType = CommandType.Text;
            return dbCommand;
        }
        #endregion

        #region 增加参数

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="dbParameterCollection"></param>
        internal void AddParameterCollection(DbCommand cmd, DbParameterCollection dbParameterCollection)
        {
            foreach (DbParameter dbParameter in dbParameterCollection)
            {
                cmd.Parameters.Add(dbParameter);
            }
        }

        /// <summary>
        /// 输出参数
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="parameterName"></param>
        /// <param name="dbType"></param>
        /// <param name="size"></param>
        public void AddOutParameter(DbCommand cmd, string parameterName, DbType dbType, int size)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Size = size;
            dbParameter.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(dbParameter);
        }

        /// <summary>
        /// 输入参数
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="parameterName"></param>
        /// <param name="dbType"></param>
        /// <param name="value"></param>
        public void AddInParameter(DbCommand cmd, string parameterName, DbType dbType, object value)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Value = value ?? DBNull.Value;
            dbParameter.Direction = ParameterDirection.Input;
            cmd.Parameters.Add(dbParameter);
        }

        /// <summary>
        /// 返回值
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="parameterName"></param>
        /// <param name="dbType"></param>
        public void AddReturnParameter(DbCommand cmd, string parameterName, DbType dbType)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(dbParameter);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="parameterName"></param>
        /// <returns></returns>
        internal DbParameter GetParameter(DbCommand cmd, string parameterName)
        {
            return cmd.Parameters[parameterName];
        }

        #endregion

        #region 执行执行

        internal DataSet ExecuteDataSet(DbCommand cmd)
        {
            //日志
            SqlLog.Add(cmd.CommandText);

            if (dbTrans == null)
            {
                Open();
            }
            else
            {
                cmd.Transaction = dbTrans;
            }
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            dbDataAdapter.Fill(ds);

            return ds;
        }

        internal DataTable ExecuteDataTable(DbCommand cmd)
        {
            //日志
            SqlLog.Add(cmd.CommandText);

            if (dbTrans == null)
            {
                Open();
            }
            else
            {
                cmd.Transaction = dbTrans;
            }
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataTable dataTable = new DataTable();
            dbDataAdapter.Fill(dataTable);

            return dataTable;
        }

        /// <summary>
        /// 这个要自己关闭
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        internal DbDataReader ExecuteReader(DbCommand cmd)
        {
            if (dbTrans == null)
            {
                Open();
            }
            else
            {
                cmd.Transaction = dbTrans;
            }
            DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            //日志
            SqlLog.Add(cmd.CommandText);

            return reader;
        }

        internal int ExecuteNonQuery(DbCommand cmd)
        {
            if (dbTrans == null)
            {
                Open();
            }
            else
            {
                cmd.Transaction = dbTrans;
            }
            int ret = cmd.ExecuteNonQuery();

            //日志
            SqlLog.Add(cmd.CommandText);

            return ret;
        }

        internal object ExecuteScalar(DbCommand cmd)
        {
            if (dbTrans == null)
            {
                Open();
            }
            else
            {
                cmd.Transaction = dbTrans;
            }
            object ret = cmd.ExecuteScalar();

            //日志
            SqlLog.Add(cmd.CommandText);

            return ret;
        }



        /// <summary>
        /// 执行事务
        /// </summary>
        public void Commit()
        {
            if (dbTrans != null)
            {
                TransType = TransType.Commit;
                this.dbTrans.Commit();
            }
            if (this.Connection.State == ConnectionState.Open)
            {
                this.Connection.Close();
            }
        }

        /// <summary>
        /// 放弃事务
        /// </summary>
        public void Rollback()
        {
            if (dbTrans != null)
            {
                TransType = TransType.Rollback;
                this.dbTrans.Rollback();
            }
            if (this.Connection.State == ConnectionState.Open)
            {
                this.Connection.Close();
            }
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="CurrentPageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        internal DataTable Paging(string sql, string orderby, int currentPageIndex, int pageSize, out int pageCount, out int count)
        {
            if (pageSize == 0)
            {
                throw new Exception("每页记录不能为0");
            }

            IPager pager = null;

            switch (DbHelper.dbProviderName)
            {
                case "System.Data.SQLite": pager = new SQLitePager(); break;
                case "System.Data.SqlClient": pager = new SQLPager(); break;
                case "MySql.Data.Entity": pager = new MysqlPager(); break;

                default: new Exception("该数据库类型还没有对应的分页方法"); break;
            }

            //总页
            count = pager.CountPaging(sql, this);

            //计算分页数量
            pageCount = count / pageSize;

            if ((count - pageCount * pageSize) > 0 || pageCount == 0)
            {
                pageCount++;
            }

            //如果超过分页页码
            if (currentPageIndex > pageCount)
            {
                currentPageIndex = pageCount;
            }

            //日志
            SqlLog.Add(sql);
            SqlLog.Add(orderby);

            return pager.Paging(sql, orderby, currentPageIndex, pageSize, this);
        }

        #endregion

        public void Open()
        {
            if (this.Connection.State != ConnectionState.Open)
            {
                Connection.Open();
            }
        }

        public void Close()
        {
            if (dbTrans == null || this.Connection.State == ConnectionState.Open)
            {
                Connection.Close();
                Connection.Dispose();
            }
        }

        public void Dispose()
        {
            this.Close();
        }

    }
}
